package com.zxh.project.areachooseapplication;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import kankan.wheel.widget.interfaces.model.CityModel;
import kankan.wheel.widget.interfaces.model.CountryModel;
import kankan.wheel.widget.interfaces.model.DistrictModel;
import kankan.wheel.widget.interfaces.model.ProvinceModel;


public class MainJsonActivity extends AppCompatActivity implements OnWheelChangedListener {

    private TextView areaTv;
    private ImageView iv_all;
    private static PopupWindow mPopTime,mPop;
    private View mAreaPicker;
    private WheelView mViewCountry,mViewProvince,mViewCity,mViewDistrict;
    private String jsonData = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_json);
        findViewById(R.id.titleBar_leftId).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainJsonActivity.this.finish();
            }
        });
        findViewById(R.id.threeBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainJsonActivity.this,JsonThreeActivity.class));
            }
        });
        jsonData = StringUtils.readAssetsTxt(this,"json_data");
        initAreaView();

        iv_all = ((ImageView) findViewById(R.id.iv_all));
        areaTv = ((TextView) findViewById(R.id.areaTv));
        findViewById(R.id.chooseLinear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                propetyAnim(iv_all);
                showTimePicker(view, mAreaPicker,MainJsonActivity.this,iv_all);
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void initAreaView() {
        initAreaPicker();
        initProvinceDatas();
        mViewCountry.setVisibleItems(7);
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        mViewCountry.setViewAdapter(new ArrayWheelAdapter<>(this,mCountryDatas,15,14));
        updatePro();
        updateCities();
        updateAreas();
    }



    private void updatePro(){
        int pCurrent = this.mViewCountry.getCurrentItem();
        this.mCurrentCountryName = this.mCountryDatas[pCurrent];
        String[] pros = ((String[]) this.mProDatasMap.get(this.mCurrentCountryName));
        if(pros == null) {
            pros = new String[]{""};
        }
        this.mViewProvince.setViewAdapter(new ArrayWheelAdapter(this, pros,15,14));
        this.mViewProvince.setCurrentItem(0);
        this.updateCities();
    }
    private void updateCities() {
        int pCurrent = this.mViewProvince.getCurrentItem();
        this.mCurrentProviceName = ((String[]) this.mProDatasMap.get(this.mCurrentCountryName))[pCurrent];
        String[] cities = (String[])this.mCitisDatasMap.get(this.mCurrentProviceName);
        if(cities == null) {
            cities = new String[]{""};
        }

        this.mViewCity.setViewAdapter(new ArrayWheelAdapter(this, cities,15,14));
        this.mViewCity.setCurrentItem(0);
        this.updateAreas();
    }
    private void updateAreas() {
        int pCurrent = this.mViewCity.getCurrentItem();
        this.mCurrentCityName = ((String[])this.mCitisDatasMap.get(this.mCurrentProviceName))[pCurrent];
        String[] areas = (String[])this.mDistrictDatasMap.get(this.mCurrentCityName);
        if(areas == null) {
            areas = new String[]{""};
        }

        this.mViewDistrict.setViewAdapter(new ArrayWheelAdapter(this, areas,15,14));
        this.mViewDistrict.setCurrentItem(0);
    }

    private void initAreaPicker() {
        mAreaPicker = View.inflate(this,R.layout.picker_area_layout22,null);
        mViewCountry = ((WheelView) mAreaPicker.findViewById(R.id.id_country));
        mViewProvince = ((WheelView) mAreaPicker.findViewById(R.id.id_province));
        mViewCity = ((WheelView) mAreaPicker.findViewById(R.id.id_city));
        mViewDistrict = ((WheelView) mAreaPicker.findViewById(R.id.id_area));
        mViewCountry.addChangingListener(this);
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);

        RelativeLayout tv_cancelStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_cancel));
        RelativeLayout tv_confirmStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_confirm));
        tv_cancelStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopTime != null){
                    mPopTime.dismiss();
                }
            }
        });
        tv_confirmStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentCountryPosition = newCountryPosition;
                currentProPosition = newProPosition;
                currentCityPosition = newCityPosition;
                currentDisPosition = newDisPosition;

                MainJsonActivity.this.mCurrentCountryName = mCountryDatas[currentCountryPosition];
                MainJsonActivity.this.mCurrentProviceName = ((String[]) MainJsonActivity.this.mProDatasMap.get(MainJsonActivity.this.mCurrentCountryName))[currentProPosition];
                MainJsonActivity.this.mCurrentCityName = ((String[])MainJsonActivity.this.mCitisDatasMap.get(MainJsonActivity.this.mCurrentProviceName))[currentCityPosition];
                String[] disNames = ((String[])MainJsonActivity.this.mDistrictDatasMap.get(MainJsonActivity.this.mCurrentCityName));
                if(disNames!=null && disNames.length > currentDisPosition){
                    MainJsonActivity.this.mCurrentDistrictName = disNames[currentDisPosition];
                }else{
                    mCurrentDistrictName = "";
                }
                areaTv.setText(mCurrentCountryName+"  "+mCurrentProviceName+"  "+mCurrentCityName+"  "+mCurrentDistrictName);

                if (mPopTime != null){
                    mPopTime.dismiss();
                }
            }
        });
    }

    protected void initProvinceDatas() {
        List countryList = new ArrayList<CountryModel>();
        AreaDataEntity areaDataEntity = JSON.parseObject(jsonData.trim(), AreaDataEntity.class);
        if(areaDataEntity==null){
            return;
        }
        for (int i = 0; i < areaDataEntity.getData().size(); i++) {
            List<ProvinceModel> provinceModelList = new ArrayList<>();
            CountryModel countryModel = new CountryModel();
            AreaDataEntity.DataBean dataBean = areaDataEntity.getData().get(i);
            countryModel.setArea_id(dataBean.getRegion_id()+"");
            countryModel.setName(dataBean.getRegion_name());
            for (int j = 0; j < dataBean.getChild().size(); j++) {
                List<CityModel> cityModelList = new ArrayList<>();
                ProvinceModel provinceModel = new ProvinceModel();
                AreaDataEntity.DataBean.ChildBeanXX childBean = dataBean.getChild().get(j);
                provinceModel.setName(childBean.getRegion_name());
                provinceModel.setArea_id(childBean.getRegion_id()+"");
                for (int k = 0; k < childBean.getChild().size(); k++) {
                    List<DistrictModel> districtModelList = new ArrayList<>();
                    CityModel cityModel = new CityModel();
                    AreaDataEntity.DataBean.ChildBeanXX.ChildBeanX childCityBean = childBean.getChild().get(k);
                    cityModel.setName(childCityBean.getRegion_name());
                    cityModel.setArea_id(childCityBean.getRegion_id()+"");
                    if(childCityBean.getChild()==null){
                        cityModelList.add(cityModel);
                        continue;
                    }
                    for (int m = 0; m < childCityBean.getChild().size(); m++) {
                        DistrictModel districtModel = new DistrictModel();
                        AreaDataEntity.DataBean.ChildBeanXX.ChildBeanX.ChildBean childDisBean = childCityBean.getChild().get(m);
                        districtModel.setArea_id(childDisBean.getRegion_id()+"");
                        districtModel.setName(childDisBean.getRegion_name());
                        districtModelList.add(districtModel);
                    }
                    cityModel.setDistrictList(districtModelList);
                    cityModelList.add(cityModel);
                }
                provinceModel.setCityList(cityModelList);
                provinceModelList.add(provinceModel);
            }
            countryModel.setProvinceList(provinceModelList);
            countryList.add(countryModel);
        }
        List provinceList;
        if(countryList!=null && !countryList.isEmpty()){
            this.mCurrentCountryName = ((CountryModel) countryList.get(0)).getName();
            List i = ((CountryModel) countryList.get(0)).getProvinceList();
            if(i!=null && !i.isEmpty()){
                this.mCurrentProviceName = ((ProvinceModel) i.get(0)).getName();
                provinceList = ((ProvinceModel) i.get(0)).getCityList();
                this.mCurrentCityName = ((CityModel) provinceList.get(0)).getName();
            }
        }
        this.mCountryDatas = new String[countryList.size()];
        this.countryAreaIds = new String[countryList.size()];
        for (int i = 0; i < countryList.size(); ++i) {
            this.mCountryDatas[i] = ((CountryModel) countryList.get(i)).getName();
            this.countryAreaIds[i] = ((CountryModel) countryList.get(i)).getArea_id();
            provinceList = ((CountryModel) countryList.get(i)).getProvinceList();
            String[] proNames = new String[provinceList.size()];
            String[] proAreaIds = new String[provinceList.size()];
            for (int j = 0; j < provinceList.size(); ++j) {
                proNames[j] = ((ProvinceModel) provinceList.get(j)).getName();
                proAreaIds[j] = ((ProvinceModel) provinceList.get(j)).getArea_id();
                List cityList = ((ProvinceModel) provinceList.get(j)).getCityList();
                String[] cityNames = new String[cityList.size()];
                String[] cityAreaIds = new String[cityList.size()];
                for(int k = 0; k < cityList.size(); ++k) {
                    cityNames[k] = ((CityModel) cityList.get(k)).getName();
                    cityAreaIds[k] = ((CityModel) cityList.get(k)).getArea_id();
                    List districtList = ((CityModel) cityList.get(k)).getDistrictList();
                    if(districtList==null){
                        continue;
                    }
                    String[] distrinctNameArray = new String[districtList.size()];
                    String[] distrinctAreaId = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for(int m = 0; m < districtList.size(); ++m) {
                        DistrictModel districtModel = new DistrictModel(((DistrictModel)districtList.get(m)).getName(), ((DistrictModel)districtList.get(m)).getZipcode(),((DistrictModel)districtList.get(m)).getArea_id());
                        distrinctArray[m] = districtModel;
                        distrinctNameArray[m] = districtModel.getName();
                        distrinctAreaId[m] = districtModel.getArea_id();
                    }
                    this.mDistrictDatasMap.put(cityNames[k], distrinctNameArray);
                    this.distAreaIdMap.put(cityNames[k],distrinctAreaId);
                }
                this.mCitisDatasMap.put(((ProvinceModel)provinceList.get(j)).getName(), cityNames);
                this.cityAreaIdMap.put(((ProvinceModel) provinceList.get(j)).getName(),cityAreaIds);
            }
            this.mProDatasMap.put(((CountryModel)countryList.get(i)).getName(), proNames);
            this.proAreaIdMap.put(((CountryModel) countryList.get(i)).getName(),proAreaIds);
        }
    }

    /**
     半透明背景出现的动画
     */
    private void propetyAnim(ImageView iv) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "alpha", 0, 0.2f, 0.5f, 0.7f, 0.9f, 1);
        animator.setDuration(500);
        animator.setRepeatCount(0);
        animator.start();
        iv.setVisibility(View.VISIBLE);
    }
    public static void showTimePicker(View parent, final View view, final Context context, final ImageView iv_all) {
        mPopTime = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopTime.setOutsideTouchable(true);
        mPopTime.setFocusable(true); // 这个很重要,涉及返回键能否取消mPop！
        mPopTime.setBackgroundDrawable(new ColorDrawable(0));
        //mPop.setAnimationStyle(R.style.AndroidImageSlider_Attractive_Rect_Blue);
        mPopTime.setAnimationStyle(R.style.AnimBottom);
        mPopTime.showAtLocation(parent, Gravity.BOTTOM, 0,0);
        mPopTime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                propetyAnim2(iv_all);
                mPopTime = null;

            }
        });

        // 重写onKeyListener
        view.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    //mPop.dismiss();
                    return true;
                }
                return true;
            }
        });

        // 点击其他地方消失
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (mPop != null && mPop.isShowing()) {


                }
                return false;
            }
        });
        mPopTime.showAsDropDown(parent);
    }
    /**
     * 半透明背景消失的动画
     * @param iv
     */
    public static void propetyAnim2(final ImageView iv){
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv,"alpha",1,0.9f,0.7f,0.5f,0.2f,0);
        animator.setDuration(500);
        animator.setRepeatCount(0);
        animator.start();
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                iv.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    protected String[] mCountryDatas,countryAreaIds;
    protected Map<String, String[]> mProDatasMap = new HashMap(),proAreaIdMap = new HashMap<>();
    protected Map<String, String[]> mCitisDatasMap = new HashMap(),cityAreaIdMap = new HashMap<>();
    protected Map<String, String[]> mDistrictDatasMap = new HashMap(),distAreaIdMap = new HashMap<>();
    protected Map<String, String> mZipcodeDatasMap = new HashMap();
    private String mCurrentCountryName;
    protected String mCurrentProviceName;
    protected String mCurrentCityName;
    protected String mCurrentDistrictName = "";
    protected String mCurrentZipCode = "";
    private int currentCountryPosition,currentProPosition,currentCityPosition,currentDisPosition;
    private int newCountryPosition,newProPosition,newCityPosition,newDisPosition;
    private int mDistrictPosition;
    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if(wheel == this.mViewCountry){
            newCountryPosition = newValue;
            mDistrictPosition = 0;
            this.updatePro();
        }else if(wheel == this.mViewProvince) {
            newProPosition = newValue;
            mDistrictPosition = 0;
            this.updateCities();
        } else if(wheel == this.mViewCity) {
            newCityPosition = newValue;
            this.updateAreas();
            mDistrictPosition = 0;
        } else if(wheel == this.mViewDistrict) {
            mDistrictPosition = newValue;
            newDisPosition = newValue;
//            this.mCurrentDistrictName = ((String[])this.mDistrictDatasMap.get(this.mCurrentCityName))[newValue];
//            this.mCurrentZipCode = (String)this.mZipcodeDatasMap.get(this.mCurrentDistrictName);
        }
    }

}
